﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Media;
using Safe_Driving.TokenUser;
using DbLinq.Data.Linq;
using System.Windows;
using System.Collections;
using System.Windows.Input;


//TODO Géer l'ajour des cours à une formation et finir boucle multi events

namespace Safe_Driving
{
    public partial class MainWindow
    {
        #region remplissage de champs

        public void RemplirZones()
        {
            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = (AppSafeDriving)token.DbApp;

            if (cbxZone.Items.Count > 0)
                cbxZone.Items.Clear();
                       
            var lesZones = (from z in app.SFZone
                            select z);
            
            foreach(SFZone sfZ in lesZones)
                cbxZone.Items.Add(sfZ.TypeZone.ToString());

            if(cbxZones.Items.Count > 0)
                cbxZone.SelectedIndex = 0;
        }

        public void RemplirTypeCours()
        {
            if (cbxTypeCours.Items.Count > 0)
                cbxTypeCours.Items.Clear();
            
            string[] namedConstants = Enum.GetNames(typeof(Type_cours_enum));
            foreach (string constant in namedConstants)
            {
                cbxTypeCours.Items.Add(constant);
            }

            if(cbxTypeCours.Items.Count > 0)
                cbxTypeCours.SelectedIndex = 0;
        }

        public void RemplirFormation()
        {
            SingletonTokenUser token = SingletonTokenUser.GetInstance();
            AppSafeDriving app = (AppSafeDriving)token.DbApp;

            if (cbxFormation.Items.Count > 0)
                cbxFormation.Items.Clear();

            var lesFormations = (from f in app.SFFormation
                                 select f);

            foreach (SFFormation sff in lesFormations)
                cbxFormation.Items.Add(sff.NoM.ToString());
        }

        #endregion

       
        /// <summary>
        /// Se produit lors d'un clic sur le bouton "Ajouter".
        /// Permet d'ajouter un nouveau client après vérification des entrées de l'utilisateur.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAjouter_Click_1(object sender, RoutedEventArgs e)
        {
            //Si la saisie est correcte, on insert le nouveau client.
            if (checkValidator())
            {
                //Récupération de la DB
                SingletonTokenUser tok = SingletonTokenUser.GetInstance();
                AppSafeDriving dbApp = tok.DbApp;

                //récupération des valeurs des champs
                string nomZone = cbxZone.SelectedItem.ToString();
                SFZone zoneChoisie = (from z in dbApp.SFZone
                                      where z.TypeZone == nomZone
                                      select z).Single();

                //initalisation des listes utilisées
                List<SFCOurs> lst_cours = new List<SFCOurs>();
                lst_cours = (List<SFCOurs>) dataGrid_planifCours.ItemsSource;
                IEnumerator lst_coursEnumerator = lst_cours.GetEnumerator();

                while (lst_coursEnumerator.MoveNext())
                {
                    SFCOurs sfc = ((SFCOurs)lst_coursEnumerator.Current);
                    sfc.IDZone = zoneChoisie.IDZone;
                    sfc.NoM = txt_createcours_name.Text;
                    sfc.TypeCOurs = cbxTypeCours.SelectedItem.ToString();
                    sfc.CapAcItemAx = Int32.Parse(txtCapaciteMax.Text);
                    sfc.TarIf = Int32.Parse(txtTarif.Text);
                    dbApp.SFCOurs.InsertOnSubmit(sfc);

                    dbApp.SubmitChanges();

                    //Si le cours appartient à une formation
                    if (cbxFormation.Text != String.Empty)
                    {
                        int idFormation = (from f in dbApp.SFFormation
                                           where f.NoM == cbxFormation.Text
                                           select f.IDFormation).Single();

                        int idCours = (from c in dbApp.SFCOurs
                                       select c.IDCOurs).Max();

                        SFSEComposeDE scd = new SFSEComposeDE
                        {
                            IDCOurs = idCours,
                            IDFormation = idFormation
                        };

                        dbApp.SFSEComposeDE.InsertOnSubmit(scd);
                    }
                }
                
                dbApp.SubmitChanges();
                Pane_Planif_cours.Visibility = Visibility.Hidden;
                //this.EC_Planification_cours.jump_week(0);
            }
        }






        /// <summary>
        /// Vérifie chaques champs
        /// </summary>
        /// <returns></returns>
        private bool checkValidator()
        {
            bool saisieOk = true;
            Verificator v = new Verificator();

            if (cbxZone.Text.Equals(String.Empty))
            {
                cbxZone.BorderBrush = Brushes.Red;
                saisieOk = false;
            }

            if (cbxTypeCours.Text.Equals(String.Empty)) 
            {
                cbxTypeCours.BorderBrush = Brushes.Red;
                saisieOk = false;
            }

            if (v.AssertMonney(txtTarif.Text) == false)
            {
                txtTarif.BorderBrush = Brushes.Red;
                saisieOk = false;
            }

            return saisieOk;
        }


        /// <summary>
        /// Permet de générer l'ItemsSource du datagrid
        /// </summary>
        /// <param name="list_final"></param>
        /// <param name="dayDate"></param>
        public void manage_cours(List<int> list_final, DateTime dayDate)
        {
            //On affiche le panneau de configuration des cours à ajouter
            Pane_Planif_cours.Visibility = Visibility.Visible;

            //On initialise les variables de collection qui serviront à remplir le datagrid dataGrid_planifCours
            IEnumerator list_finalEnumerator = list_final.GetEnumerator();
            int last_index, index_current;

            DateTime debut, fin;
            List<SFCOurs> lst_cours = new List<SFCOurs>();

            if (list_final.Count == 2)
            {
                list_finalEnumerator.MoveNext();
                index_current = (int)list_finalEnumerator.Current;
                list_finalEnumerator.MoveNext();
                last_index = (int)list_finalEnumerator.Current;

                debut = DateTime.Parse(dayDate.Year + "/" + dayDate.Month + "/" + dayDate.Day + " " + index_current.ToString() + ":00:00");
                fin = DateTime.Parse(dayDate.Year + "/" + dayDate.Month + "/" + dayDate.Day + " " + last_index.ToString() + ":00:00");
                lst_cours.Add(createCours(debut, fin));

            }
            else
            {
                //Move other the 0 index
                list_finalEnumerator.MoveNext();
                
                while (list_finalEnumerator.MoveNext())
                {
                    index_current = (int)list_finalEnumerator.Current;
                    list_finalEnumerator.MoveNext();
                    last_index = (int)list_finalEnumerator.Current;

                    debut = DateTime.Parse(dayDate.Year + "/" + dayDate.Month + "/" + dayDate.Day + " " + index_current.ToString() + ":00:00");
                    fin = DateTime.Parse(dayDate.Year + "/" + dayDate.Month + "/" + dayDate.Day + " " + (last_index + 1).ToString() + ":00:00");
                    lst_cours.Add(createCours(debut, fin));
                }
            }

            dataGrid_planifCours.ItemsSource = lst_cours;

        }

        public void delete_cours(int id_cours)
        {
            SingletonTokenUser tok = SingletonTokenUser.GetInstance();
            
            SFCOurs cours = (from c in tok.DbApp.SFCOurs
                             where c.IDCOurs == id_cours
                             select c).SingleOrDefault();

            SFSEComposeDE scd = (from s in tok.DbApp.SFSEComposeDE
                                 where s.IDCOurs == cours.IDCOurs
                                 select s).SingleOrDefault();

            if ( scd != null ) {
                tok.DbApp.SFSEComposeDE.DeleteOnSubmit(scd);
            }


            tok.DbApp.SFCOurs.DeleteOnSubmit(cours);
            tok.DbApp.SubmitChanges();
            //this.EC_Planification_cours.jump_week(0);
        }


        /// <summary>
        /// Genére une objet SFcours
        /// </summary>
        /// <param name="debut"></param>
        /// <param name="fin"></param>
        /// <returns></returns>
        private SFCOurs createCours(DateTime debut, DateTime fin)
        {
            SFCOurs s = new SFCOurs();
            s.DateDebut = debut;
            s.DateFIn = fin;

            return s;
        }

        private void img_close_createcours_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Pane_Planif_cours.Visibility = Visibility.Hidden;
        }

    }
}
